import * as G2 from '@antv/g2';
import { useEffect } from "react";
import './error-metrics.less';

let chart: any;

function render(list: any[]) {
  let data = list;

  let days: any = {}

  data.forEach((it: any) => {
    const d = it.time.substr(0, 10)
    if (days[d]) {
      days[d] += 1;
    } else {
      days[d] = 1
    }
  })

  data = Object.keys(days).map((key) => {
    return {
      time: key,
      value: days[key]
    }
  })

  if (chart === undefined) {
    chart = new G2.Chart({
      container: 'mountNode',
      height: 280,
      width: 1200,
      forceFit: true,
      padding: [40, 40, 40, 40],
    });

    chart.axis('time', {
      label: {
        textStyle: {
          fill: '#aaaaaa'
        }
      }
    });

    chart.axis('value', {
      label: {
        textStyle: {
          fill: '#aaaaaa'
        }
      }
    });

    chart.line().position('time*value');
  }

  chart.source(data);

  chart.render();
}

interface ErrorMetricsProps {
  metrics: any[]
}

export default function ErrorMetrics(props: ErrorMetricsProps) {
  useEffect(() => {
    render(props.metrics);
    return function () {
      chart.destroy();
      chart = undefined;
    }
  }, [props.metrics])

  return (
    <div className={"metrics-chart"} style={{
    }} id="mountNode" />
  )
}